<template>
  <BasicModal v-bind="$attrs" @register="registerModal" :defaultFullscreen="true" :destroyOnClose="true" :title="modalTitle" :width="800" :showCancelBtn="false" :showOkBtn="false" @ok="handleSubmit">
    <div class="flex">
      <div class="w-1/4">
        <p class="treeTitle">{{ title }}</p>
        <a-tree v-model:selectedKeys="selectedKeys" :tree-data="treeDataBase" @select="changTreeNodefn" :fieldNames="{ title: treeTitle, key: treeValue }" />
      </div>
      <!--引用表格-->
      <div class="w-3/4">
        <BasicTable @register="registerCustomTable" />
      </div>
    </div>
  </BasicModal>
</template>

<script lang="ts" name="com.hzzenith.km.emp-hubTeamAdd" setup>
import { ref, computed, unref, defineProps } from 'vue';
import { BasicTable, useTable, TableAction } from '/@/components/Table';
import { useModal, BasicModal, useModalInner } from '/@/components/Modal';
import { BasicForm, useForm } from '/@/components/Form/index';
import { useListPage } from '/@/hooks/system/useListPage';
import HubTeamAddModal from './components/HubTeamAddModal.vue';
// import {columns, searchFormSchema} from './HubTeamAdd.data';
import { getPeriodTree } from '/@/api/common/api';
import { useMessage } from '/@/hooks/web/useMessage';
import { Modal } from 'ant-design-vue';
import dayjs from 'dayjs';

// 轻提醒
const { createMessage: $message } = useMessage();
// Emits声明
const emit = defineEmits(['register', 'success']);
const props = defineProps({
  columns: {
    type: Array,
    default: [],
  },
  searchFormSchema: {
    type: Array,
    default: [],
  },
  treeDataBase: {
    type: Array,
    default: [],
  },
  pageList: Function,
  importHistory: Function,
  fetchHistoryList: Function,
  treeTitle: String,
  treeValue: String,
  title: String,
  showOrg: {
    type: Boolean,
    default: false,
  },
});

const pageParams = {
  [`${props.treeValue}`]: '',
};

const orgCode = ref('');


const modalTitle = props.showOrg ? '典型工分库导入' : '历史指标库导入';

const [registerModal, { setModalProps, closeModal }] = useModalInner((data) => {
  console.log('data', data);
  selectedKeys.value = [];
  orgCode.value = data.orgCode;
  let form = getForm();
  form.setFieldsValue({
    periodCode: data.periodCode,
  });
});

const historySearchFormSchema = [
  {
    label: '历史周期',
    field: 'periodCode1',
    component: 'ApiTreeSelect',
    componentProps: {
      api: getPeriodTree,
      fieldNames: {
        children: 'child',
        label: 'periodName',
        value: 'periodCode',
      },
      onChange: (e) => {
        reload({
          searchInfo: {
            orgCode: orgCode.value,
            [`${props.treeValue}`]: pageParams[props.treeValue],
            periodCode: e,
          },
        });
      },
    },
    required: true,
    defaultValue: dayjs().format('YYYY'),
  },
  {
    label: '考核周期',
    field: 'periodCode',
    component: 'Input',
    required: true,
    defaultValue: dayjs().format('YYYY'),
    dynamicDisabled: () => {
      return true;
    },
  },
];

// 提交事件
const handleSubmit = () => {
  console.log('提交');
};
// 树形控件
const selectedKeys = ref([]);

const { prefixCls, tableContext, onImportXls } = useListPage({
  tableProps: {
    // title: 'hub_team_add',
    api: props.pageList,
    columns: props.columns,
    canResize: false,
    dataSource: [],
    showIndexColumn: true,
    rowKey: 'id',
    beforeFetch: (params) => {
      return Object.assign(params, { orgCode: orgCode.value });
    },
    formConfig: {
      //labelWidth: 120,
      schemas: historySearchFormSchema,
      autoSubmitOnEnter: true,
      showAdvancedButton: false,
      fieldMapToNumber: [],
      fieldMapToTime: [],
      submitButtonOptions: {
        text: '导入目标周期',
      },
      showResetButton: false,
      submitFunc: importList,
    },
    immediate: true, // 班组表格放到orgCode拿到值之后再加载 false不会立即加载,reload()之后再加载
  },
});

const [registerCustomTable, { getForm, reload, getDataSource }, { rowSelection, selectedRowKeys }] = tableContext;

// emit('fetchHistoryList', reload)

function importList() {
  let tableData = getDataSource();
  let formData = getForm().getFieldsValue();
  if (!formData.periodCode) {
    $message.error('请选择历史周期');
    return;
  }
  //  else if (!pageParams[props.treeValue]) {
  //   $message.error('请选择左侧类型');
  //   return;
  // }

  let savaData = {
    datas: tableData,
    [`${props.treeValue}`]: pageParams[props.treeValue],
    periodCode: formData.periodCode,
    periodCode1: formData.periodCode1,
    orgCode: orgCode.value,
  };

  Modal.confirm({
    content: '确认导入该周期数据吗？',
    okText: '确认',
    cancelText: '取消',
    onOk: () => {
      props.importHistory(savaData).then((res) => {
        if (res) {
          $message.success('导入成功');
          closeModal();
          emit('success');
        }
      });
    },
    onCancel: () => {
      $message.info('已取消');
    },
  });
};

// 树点击回调
function changTreeNodefn(selectedKeys, { node }) {
  pageParams[props.treeValue] = node[props.treeValue];
  // pageParams.value.indexTypeName = node.indexTypeName;
  reload({
    searchInfo: {
      orgCode: orgCode.value,
      [`${props.treeValue}`]: node[props.treeValue],
    },
  });
}
</script>
